// 性能监控工具
class PerformanceMonitor {
  constructor() {
    this.metrics = new Map()
    this.observers = new Map()
    this.isEnabled = true
  }

  // 开始计时
  startTimer(name) {
    if (!this.isEnabled) return
    
    this.metrics.set(name, {
      startTime: performance.now(),
      endTime: null,
      duration: null
    })
  }

  // 结束计时
  endTimer(name) {
    if (!this.isEnabled) return
    
    const metric = this.metrics.get(name)
    if (!metric) {
      console.warn(`性能监控: 未找到计时器 "${name}"`)
      return
    }

    metric.endTime = performance.now()
    metric.duration = metric.endTime - metric.startTime

    // 记录慢操作
    if (metric.duration > 1000) {
      console.warn(`性能警告: "${name}" 耗时 ${metric.duration.toFixed(2)}ms`)
    }

    return metric.duration
  }

  // 测量函数执行时间
  async measureAsync(name, fn) {
    this.startTimer(name)
    try {
      const result = await fn()
      this.endTimer(name)
      return result
    } catch (error) {
      this.endTimer(name)
      throw error
    }
  }

  // 测量同步函数执行时间
  measureSync(name, fn) {
    this.startTimer(name)
    try {
      const result = fn()
      this.endTimer(name)
      return result
    } catch (error) {
      this.endTimer(name)
      throw error
    }
  }

  // 获取性能指标
  getMetrics() {
    const result = {}
    for (const [name, metric] of this.metrics) {
      if (metric.duration !== null) {
        result[name] = {
          duration: metric.duration,
          startTime: metric.startTime,
          endTime: metric.endTime
        }
      }
    }
    return result
  }

  // 清除性能指标
  clearMetrics() {
    this.metrics.clear()
  }

  // 获取平均执行时间
  getAverageDuration(name) {
    const metrics = Array.from(this.metrics.values())
      .filter(m => m.duration !== null)
    
    if (metrics.length === 0) return 0
    
    const total = metrics.reduce((sum, m) => sum + m.duration, 0)
    return total / metrics.length
  }

  // 监控DOM变化
  observeDOM(target, callback, options = {}) {
    const observer = new MutationObserver((mutations) => {
      if (this.isEnabled) {
        callback(mutations)
      }
    })
    
    observer.observe(target, {
      childList: true,
      subtree: true,
      attributes: true,
      ...options
    })
    
    this.observers.set(target, observer)
    return observer
  }

  // 停止DOM监控
  disconnectObserver(target) {
    const observer = this.observers.get(target)
    if (observer) {
      observer.disconnect()
      this.observers.delete(target)
    }
  }

  // 监控内存使用
  getMemoryInfo() {
    if (performance.memory) {
      return {
        usedJSHeapSize: performance.memory.usedJSHeapSize,
        totalJSHeapSize: performance.memory.totalJSHeapSize,
        jsHeapSizeLimit: performance.memory.jsHeapSizeLimit
      }
    }
    return null
  }

  // 监控网络性能
  getNetworkInfo() {
    if ('connection' in navigator) {
      return {
        effectiveType: navigator.connection.effectiveType,
        downlink: navigator.connection.downlink,
        rtt: navigator.connection.rtt
      }
    }
    return null
  }

  // 生成性能报告
  generateReport() {
    const metrics = this.getMetrics()
    const memoryInfo = this.getMemoryInfo()
    const networkInfo = this.getNetworkInfo()
    
    return {
      timestamp: new Date().toISOString(),
      metrics,
      memoryInfo,
      networkInfo,
      summary: {
        totalOperations: Object.keys(metrics).length,
        averageDuration: Object.values(metrics).reduce((sum, m) => sum + m.duration, 0) / Object.keys(metrics).length || 0,
        slowestOperation: Object.entries(metrics).reduce((max, [name, metric]) => 
          metric.duration > max.duration ? { name, ...metric } : max, 
          { name: '', duration: 0 }
        )
      }
    }
  }

  // 启用/禁用监控
  setEnabled(enabled) {
    this.isEnabled = enabled
  }
}

// 创建全局性能监控实例
export const performanceMonitor = new PerformanceMonitor()

// 性能装饰器
export function measure(name) {
  return function(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value

    descriptor.value = async function(...args) {
      return performanceMonitor.measureAsync(name, () => originalMethod.apply(this, args))
    }

    return descriptor
  }
}

// 防抖装饰器
export function debounce(wait) {
  return function(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value
    let timeout

    descriptor.value = function(...args) {
      clearTimeout(timeout)
      return new Promise(resolve => {
        timeout = setTimeout(() => {
          resolve(originalMethod.apply(this, args))
        }, wait)
      })
    }

    return descriptor
  }
}

// 节流装饰器
export function throttle(limit) {
  return function(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value
    let inThrottle = false

    descriptor.value = function(...args) {
      if (!inThrottle) {
        inThrottle = true
        const result = originalMethod.apply(this, args)
        setTimeout(() => inThrottle = false, limit)
        return result
      }
    }

    return descriptor
  }
}

export default performanceMonitor 